
import DataManager from "../DataManager";
import { API_TYPE, ApiType } from "./SDKUtil";

const { ccclass, property } = cc._decorator;
@ccclass
export default class WXSdk {

    protected static _instance: WXSdk = null;
    private _shareTime: number;
    private isShared: boolean = false;
    private isGroupShared: boolean = false;
    private _shareGroupCb: any = null;
    private _shareCb: any = null;
    private _shareFb: any = null;
    private _intersitialAd: any;
    InterstitialAdId: any;
    private _bannerAds: any = null;
    private _rewardedVideoAd = null;
    WatchVAD: boolean = false;
    private _VideoAdcb = null;
    private _VideoAdfb = null;
    private _systemInfo: any;

    public static get Instance(): WXSdk {
        if (WXSdk._instance == null) {
            WXSdk._instance = new WXSdk();
        }
        return WXSdk._instance;
    }
    BannerIds: any = ["广告ID"];
    RewardedVideoAdId: any = ["广告ID"];

    public data: any = null;
    public ShareTitle: string[] = [
        "据说好看的人到哪都是最高分",
        "快看，你是超不过我的！",
        "噗！我需要您的帮助",
        "@你，我已经超过了，快来和我决斗",
        "实力不允许我低调"
    ];
    public ShareImgId: string = '通过 MP 系统审核的图片编号'; // 通过 MP 系统审核的图片编号
    public ShareImgUrl: string = '通过 MP 系统审核的图片编号';

    init() {
        let sysInfo = window["wx"].getSystemInfoSync();
        this._systemInfo = sysInfo;
        this.createBannerAds();
    }

    init2() {
        this.createRewardedVideoAd();
    }

    showInterstitialAd() {
        if (!window["wx"]) {
            return;
        }
        if (!this._intersitialAd) {
            this.createInterstitialAd();
            return;
        }
        this._intersitialAd.show();
    }


    showRewardedVideoAd(index, cb, fb) {
        if (!window["wx"]) {
            return;
        }
        this._VideoAdcb = cb;
        this._VideoAdfb = fb;
        if (this._rewardedVideoAd) {
            this._rewardedVideoAd.show();
        }
        else {
            this.createRewardedVideoAd();
            setTimeout(() => {
                if (this._rewardedVideoAd) this._rewardedVideoAd.show();
            }, 1000)
        }
    }



    showBannerAd(index) {
        index = 0;
        if (!window["wx"]) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        for (let i = 0; i < this._bannerAds.length; i++) {
            if (i != index) {
                this._bannerAds[i].hide();
            }
        }
        let node = cc.find("gamePanel");
        if (node && node.getComponent("gamePanel") && node.getComponent("gamePanel").gameState) return;
        console.log(index)
        if (this._bannerAds[index]) {
            console.log("this._bannerAds", this._bannerAds[index])
            this._bannerAds[index].show();
        }
    }

    hideBannerAd(index) {
        if (!window["wx"]) {
            return;
        }
        this.hideBannerAds();
        if (this._bannerAds && index < this._bannerAds.length && this._bannerAds[index]) {
            this._bannerAds[index].hide();
        }
    }

    //隐藏所有广告
    hideBannerAds() {
        if (!window["wx"]) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        if (this._bannerAds && this._bannerAds.length != null) {
            if (this._bannerAds.length > 0) {
                for (var i = 0; i < this._bannerAds.length; i++) {
                    if (this._bannerAds && this._bannerAds[i]) {
                        this._bannerAds[i].hide();
                    }
                }
            }
        }
    }

    createBannerAds() {
        let winSize = this._systemInfo || window["wx"].getSystemInfoSync(); //wx.getSystemInfoSync();
        let bannerHeight = 130;
        let bannerWidth = 300;

        this._bannerAds = [];
        var length = this.BannerIds.length;
        for (let i = 0; i < length; i++) {
            //@ts-ignore
            let banner = wx.createBannerAd({
                adUnitId: this.BannerIds[i],
                adIntervals: 30,
                style: {
                    left: (winSize.windowWidth - bannerWidth) / 2,
                    top: winSize.windowHeight - bannerHeight,
                    width: bannerWidth,
                }
            });
            banner.onError(function (res) {
                console.log('banner, ', res);
            });
            this._bannerAds[i] = banner;
        }
    }

    createInterstitialAd() {
        let self = this;

        if (this._intersitialAd) {
            return;
        }

        //@ts-ignore
        this._intersitialAd = wx.createInterstitialAd({
            adUnitId: this.InterstitialAdId,
        })

        //console.log('this._intersitialAd=' + this._intersitialAd);
        this._intersitialAd.onError(function (res) {
            console.log('_intersitialAd, errMsg=' + JSON.stringify(res));
            // wx.showToast({
            //     title: 'load ad failed！',
            //     icon: 'success',
            //     duration: 2000
            // });
            setTimeout(() => {
                self.createInterstitialAd();
            }, 500);
        });
        this._intersitialAd.onClose(function (res) {
            console.log('_intersitialAd, onClose, res=' + JSON.stringify(res));
        });

        if (!this._intersitialAd) {
            setTimeout(() => {
                this.createInterstitialAd();
            }, 500);
            return;
        }
        this._intersitialAd.load();
        //this._intersitialAd.show();
    }

    shareAppMessage(i = 0, cb?, fb?) {
        console.log('shareAppMessage...');
        let self = this;
        let msg = self.ShareTitle[i];
        //@ts-ignore
        window["wx"].shareAppMessage({
            title: msg,
            imageUrlId: self.ShareImgId,
            imageUrl: self.ShareImgUrl,
            query: "id:" + DataManager.Instance.getPlayerId(),
        });
        this._shareTime = this.getCurTime();
        this.isShared = true;
        this._shareCb = cb;
        this._shareFb = fb;
    }

    createRewardedVideoAd(number = 0) {
        if (this._rewardedVideoAd) {
            return;
        }
        if (!window["wx"]) {
            return;
        }
        //@ts-ignore
        this._rewardedVideoAd = wx.createRewardedVideoAd({
            adUnitId: this.RewardedVideoAdId[0]
        });

        this._rewardedVideoAd.onError(function (res) {
            console.log('onError, _rewardedVideoAd, res=' + JSON.stringify(res));
        });

        this.WatchVAD = false;
        this._rewardedVideoAd.onClose((res) => {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined
            console.log(res)
            if (res && res.isEnded || res === undefined) {
                this.WatchVAD = true;
                if (this._VideoAdcb) this._VideoAdcb();
                DataManager.Instance.setVideoNum(1);
                this._VideoAdcb = null;
            }
            else {
                // 播放中途退出，不下发游戏奖励
                if (this._VideoAdfb) this._VideoAdfb();
                this._VideoAdfb = null;
            }
        });
        this._rewardedVideoAd.onError((err) => {
            if (this._VideoAdfb) this._VideoAdfb();
            this._VideoAdfb = null;
        });
        this._rewardedVideoAd.load();
        //this._rewardedVideoAd.show();
    }


    shareToGroupAppMessage(cb) {
        console.log('shareAppMessage...');
        let self = this;
        this._shareGroupCb = cb;
        //@ts-ignore
        window["wx"].shareAppMessage({
            title: self.ShareTitle[0],
            imageUrlId: self.ShareImgId,
            imageUrl: self.ShareImgUrl,
            query: "id:" + DataManager.Instance.getPlayerId(),
        });
        this.isGroupShared = true;
    }

    public getUserName(): string {
        if (WXSdk.Instance.data == null) {
            return "玩家";
        }
        else {
            return WXSdk.Instance.data.userInfo.nickName;
        }
    }
    public getAvatarURL(): string {
        if (WXSdk.Instance.data == null) {
            return "";
        }
        else {
            return WXSdk.Instance.data.userInfo.avatarUrl;
        }
    }
    public getLoginCode(): string {
        if (WXSdk.Instance.data == null) {
            return "";
        }
        else {
            return WXSdk.Instance.data.userInfo.avatarUrl;
        }
    }

    postDataToWX(score, now) {
        //向微信保存最高分数
        var kvDateList = new Array();
        kvDateList.push({
            key: "score",
            value: score + "",
        });
        kvDateList.push({
            key: "now",
            value: now + "",
        });
        console.log("托管游戏数据")
        console.log(kvDateList)
        //托管游戏数据
        //@ts-ignore
        wx.setUserCloudStorage({
            KVDataList: kvDateList,
            success: (res) => {
                console.log("托管游戏数据wx.setUserCloudStorage success");
                console.log(res);
            },
            fail: (res) => {
                console.log("托管游戏数据wx.setUserCloudStorage fail");
                console.log(res);
            }
        });
    }

    showShare() {
        //@ts-ignore
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
        //@ts-ignore
        wx.onShow((res) => {
            let curTime = this.getCurTime();
            if (this.isShared && (curTime - this._shareTime) >= 3 && (curTime - this._shareTime) < 60) {
                console.log("分享成功");
                this._shareTime = curTime;
                this.isShared = false;
                if (this._shareCb) {
                    this._shareCb();
                    this._shareCb = null;
                }
            }
            else if (this.isShared) {
                if (this._shareFb) {
                    this._shareFb();
                    this._shareFb = null;
                }
                this.isShared = false;
            }
            let shareTicket = res ? res.shareTicket : "";
            if (shareTicket && this.isGroupShared) {
                if (this._shareGroupCb) {
                    this._shareGroupCb(shareTicket);
                    this._shareGroupCb = null;
                }
                this.isGroupShared = false;
            }
        });
        //@ts-ignore
        wx.onShareAppMessage(() => {
            return {
                title: this.ShareTitle[0],
                imageUrlId: this.ShareImgId,
                imageUrl: this.ShareImgUrl,
            }
        });
    }


    public Login(cb?) {
        this.showShare();
        //@ts-ignore
        let sysInfo = wx.getSystemInfoSync();
        this._systemInfo = sysInfo;
        let width = sysInfo.screenWidth;
        let height = sysInfo.screenHeight;
        let self = this;
        console.log("请求用户信息");
        //@ts-ignore
        wx.getSetting({
            success(res) {
                console.log("res.authSetting:" + res.authSetting);
                if (res.authSetting["scope.userInfo"]) {
                    console.log("用户已授权");
                    //@ts-ignore
                    wx.getUserInfo({
                        success(res) {
                            console.log("用户授权：" + res);
                            console.log(res);
                            WXSdk.Instance.data = res;
                            //TODO: others
                            console.log("nickName:" + WXSdk.Instance.getUserName());
                            console.log("avatarUrl:" + WXSdk.Instance.getAvatarURL());
                            self.setLogin(cb, res);
                            let sysInfo = window["wx"].getSystemInfoSync();
                            self._systemInfo = sysInfo;
                        }
                    });
                }
                else {
                    console.log("用户未授权");
                    //用户未授权的话，全屏覆盖一个按钮，用户点击任意地方都会触发onTap()，弹出授权界面
                    //@ts-ignore
                    let button = wx.createUserInfoButton({
                        type: 'text',
                        text: '',//不显示文字
                        style: {
                            left: 0,
                            top: 0,
                            width: width,
                            height: height,
                            // lineHeight: 40,
                            backgroundColor: '#00000000',//设置按钮透明
                            color: '#ffffff',
                            textAlign: 'center',
                            fontSize: 16,
                            // borderRadius: 4
                        }
                    });
                    button.onTap(
                        (res) => {
                            if (res.userInfo) {
                                console.log("用户授权：" + res);
                                console.log(res);
                                WXSdk.Instance.data = res;
                                self.setLogin(cb, res);
                                //TODO：others
                                button.destroy();//此时删除按钮
                            }
                            else//说明用户点击 不允许授权的按钮
                            {
                                console.log("用户拒绝授权");
                                button.destroy();
                                self.Login(cb);
                            }
                        }
                    );
                }
            }
        });
    }

    setLogin(cb?, data = {}) {
        // let isWeChat = (cc.sys.platform === cc.sys.WECHAT_GAME);
        if (ApiType != API_TYPE.VX) {
            return;
        }
        let self = this;
        //@ts-ignore
        wx.login({
            success(res) {
                console.log('请求登录');
                console.log(res)
                if (res.code) {
                    console.log('微信登录成功！')
                    console.log(res)
                    //发起网络请求
                    if (cb) cb(res, data);
                } else {
                    setTimeout(() => {
                        self.setLogin(cb, data);
                    }, 500);
                    console.log('登录失败！' + res.errMsg)
                }
            },
            complete() {
                console.log('登录调用完成');
            },
            fail() {
                console.log('再次登录');
                setTimeout(() => {
                    self.setLogin(cb, data);
                }, 500);
            },
        })
    }

    /**获取当前时间戳：秒 */
    getCurTime() {
        return Math.ceil(Date.now() / 1000);
    }
}